<?php
namespace app\manage\controller;

use app\common\model\SendSms;
use app\manage\model\Action;
use app\manage\model\AdminUser;
use app\manage\model\PlatformType;
use app\manage\model\RoleAction;
use think\Controller;
use think\Validate;
use think\Db;
use Config;
use app\common\model\TokenCheck;
use app\manage\model\OperationLog;
use app\manage\model\Role;
use app\manage\model\UserRole;
use app\manage\model\Code;

class AdminLogin extends Controller{
	public function __construct()
	{
		$this->token_check = new TokenCheck();
	}
	/**
	 * 登陆接口
	 * 该接口已配置不验证token
	 * @param admin_tel  string  手机号码
	 * @param admin_pwd  string  密码	 
	 * @return token  string
	 */
	public function adminLogin(){
		$input = input();
		$validate = new Validate([
            ['admin_tel', 'require|max:11|/^1[3-8]{1}[0-9]{9}$/', '手机号码不能为空|手机号码不能超过11个字符|手机号码格式不正确'],  
            ['admin_pwd', 'require|min:6|max:256', '密码不能为空|密码长度不能小于6位|密码长度不能大于12位'],
        ]);
        if(!$validate->check($input))
        {
        	returnJson(-1001,  $validate->getError())->send();die;
        }

        //密码前端加密后传过来，防止中途截获，密码加密规则 密码拼接api_sign_key后md5
        $where['admin_tel'] = trim( $input['admin_tel'] );
        $res = Db::name( 'admin_user' )
              ->field( "admin_id,name, start_login_time, role_id, admin_sign,admin_status,admin_pwd")
              ->where( $where )
              ->find();

        $model = new AdminUser();
        $key = $model->getKey($res['admin_id']);
        if( $res){
            if ($res['admin_status'] == 2) {
                returnJson(-2001,"账号被禁用")->send();die;
            }
            if ($res['admin_status'] == 3) {
                returnJson(-2001,"账号被删除")->send();die;
            }
            if ($res['admin_pwd'] !== md5(trim($input['admin_pwd']) . $key['key'])) {
                returnJson(-1008,"账号或者密码错误")->send();die;
            }

            // 若是首次登陆，则提醒用户设置密码
            if ($res['start_login_time'] == 0) {
                returnJson(205,"首次登陆，请设置密码")->send();die;
            }

            //验证用户是否启用
            if ($res['admin_status'] !== 1) {
                returnJson(-2007,"账户被禁用")->send();die;
            }

            // 验证密码
            if (md5($input['admin_pwd'] . $key['key']) !== $res['admin_pwd']) {
                returnJson(-1008,"账号或者密码错误")->send();die;
            }

            $ip = get_real_ip();
            $time = time();
        	//生成token，以后每次接口请求，都带token，否则未登录，token参与sign签名  
        	//根据业务。记录登录需要的信息或者日志，比如登录次数，登录时间，登录ip等
            $data = array(
                'create_time' => $time,
                'log_user' => $res['admin_id'],
                'operation' => 1,
                'extra' => $ip
            );
            $resAdd = OperationLog::create($data);
            if (!$resAdd) {
                returnJson(-2001,"服务器错误")->send();die;
            }

            // 判断是否是第一次登陆，若是第一次登陆，则更新第一次登陆时间
            if ($res['start_login_time'] == 0) {
                $updateData['start_login_time'] = $time;
            }

            // 更新登陆次数、最后一次登陆ip，最后一次登陆时间
            $updateData['last__ip'] = $ip;
            $updateData['last_time'] = $time;
            $resUpdate=Db::name('admin_user')->where(['admin_id'=>$res['admin_id']])->update($updateData);
            if ($resUpdate) {
                $resUpdate=Db::name('admin_user')->where(['admin_id'=>$res['admin_id']])->setInc('login_num', 1);
                if ($resUpdate) {
                    // 返回页面权限，筛选菜单
                    $data_per = array();
                    if (intval($res['admin_id']) == 1) {
                        $model = new Action();
                        $permission = $model->m_list_y();
                        foreach ($permission as $value) {
                            $a = ['100'];
                            if (in_array($value['id'], $a)) continue;
                            array_push($data_per, $value['id']);
                        }
                    } elseif (intval($res['admin_sign']) == 1) {
                        $model = new Action();
                        $permission = $model->m_list_y();
                        foreach ($permission as $value) {
//                            if ($value['id'] >= config('permission')['min'] && $value['id'] <= config('permission')['max'])
//                            if (intval($res['admin_id']) == 1) {
//                                array_push($data_per, $value['id']);
//                            } else {
                            // 普通管理员不能有增加平台管理员的权限
                            $a = ['100'];
                            if (in_array($value['id'], $a)) continue;
                            array_push($data_per, $value['id']);
//                            }

                        }
                    } else {
                        $model = new RoleAction();
                        $detail = $model->detail_q($res['role_id']);
                        $model_a = new Role();
                        $role_detail = $model_a->detail($res['role_id']);
                        if ($role_detail['is_platform'] == 1) {
                            $model = new Action();
                            $permission = $model->m_list_y();
                            foreach ($permission as $value) {
                                $a = ['100'];
                                if (in_array($value['id'], $a)) continue;
                                array_push($data_per, $value['id']);
                            }
                        } else {
                            if ($detail['all_action'] == '') {
                                $data_per = [];
                            } else {
                                $data_per = explode(',', $detail['all_action']);
                                foreach ($data_per as $k => $value) {
                                    $a = ['100'];
                                    if (isset($value['id']) && (in_array($value['id'], $a))) unset($data_per[$k]);
                                }
                                $data_per = array_merge_recursive($data_per);
                            }

                        }

                    }

                    $model = new PlatformType();
                    $data = $model->getAll();
                    $data[0]['admin_name'] = $res['name'];
                    if ($res['admin_id'] == 1) $res['admin_sign'] = 0;//超管返回：0 平台账号：1 员工：2
                    returnJson(200,'操作成功', $this->token_check->createToken($res['admin_id']), $data_per, $res['admin_id'], $res['admin_sign'], $data)->send();die;
                } else {
                    returnJson(-2001,"服务器错误")->send();die;
                }
            } else {
                returnJson(-2001,"服务器错误")->send();die;
            }

        }else{
        	returnJson(-1008,"账号或者密码错误")->send();die; 
        }
	}
   //测试接口
   //已经在check方法中写了验证 token的方法
   //直接访问会报错"msg": "token不能为空"
	public function test(){
        echo 1;die;
	}

    /**
     * 首次登陆设置密码并登陆
     * @param admin_tel 修改密码的账户
     * @param  admin_pwd    密码
     */
	public function setFirstPassword() {
        // 使用普遍的修改密码规则进行判定
        $input = input();
        $admin_pwd = isset($input['admin_pwd']) ? trim($input['admin_pwd']) : "";
        $admin_tel = isset($input['admin_tel']) ? trim($input['admin_tel']) : "";

        $where['admin_tel'] = $admin_tel;
//        $where['admin_status'] = 1; //是否启用
        $res = Db::name( 'admin_user' )
            ->where( $where )
            ->find();
        if ($res) {
            if ($res['admin_status'] == 2) {
                returnJson(-2001,"账号被禁用")->send();die;
            }
            if ($res['admin_status'] == 3) {
                returnJson(-2001,"账号被删除")->send();die;
            }
            $updateData['admin_pwd'] = md5($admin_pwd . $res['key']);
            $updateData['start_login_time'] = time();
            $resUpdate=Db::name('admin_user')->where(['admin_id'=>$res['admin_id']])->update($updateData);
            if ($resUpdate) { //更新密码成功
                $ip = get_real_ip();
                $time = time();
                $data = array(
                    'create_time' => $time,
                    'log_user' => $res['admin_id'],
                    'operation' => 1,
                    'extra' => $ip
                );
                $resAdd = OperationLog::create($data);
                if (!$resAdd) {
                    returnJson(-2001,"服务器错误")->send();die;
                }

                $updateData['last__ip'] = $ip;
                $updateData['last_time'] = $time;
                $resUpdate=Db::name('admin_user')->where(['admin_id'=>$res['admin_id']])->update($updateData);
                if ($resUpdate) { //更新登陆信息成功
                    $resUpdate=Db::name('admin_user')->where(['admin_id'=>$res['admin_id']])->setInc('login_num', 1);
                    if ($resUpdate) {
                        // 返回页面权限，筛选菜单
                        $data_per = array();
                        if (intval($res['admin_id']) == 1 || intval($res['admin_sign']) == 1) {
                            $model = new Action();
                            $permission = $model->m_list_y();
                            foreach ($permission as $value) {
//                            if ($value['id'] >= config('permission')['min'] && $value['id'] <= config('permission')['max'])
                                if (intval($res['admin_id']) == 1) {
                                    array_push($data_per, $value['id']);
                                } else {
                                    $a = ['100'];
                                    if (in_array($value['id'], $a)) continue;
                                    array_push($data_per, $value['id']);
                                }

                            }
                        } else {
                            $model = new RoleAction();
                            $detail = $model->detail_q($res['role_id']);
                            $model_a = new Role();
                            $role_detail = $model_a->detail($res['role_id']);
                            if ($role_detail['is_platform'] == 1) {
                                $model = new Action();
                                $permission = $model->m_list_y();
                                foreach ($permission as $value) {
                                    $a = ['100'];
                                    if (in_array($value['id'], $a)) continue;
                                    array_push($data_per, $value['id']);
                                }
                            } else {
                                if ($detail['all_action'] == '') {
                                    $data_per = [];
                                } else {
                                    $data_per = explode(',', $detail['all_action']);
                                    foreach ($data_per as $k => $value) {
                                        $a = ['100'];
                                        if (in_array($value, $a)) unset($data_per[$k]);
                                    }
                                    $data_per = array_merge_recursive($data_per);
                                }

                            }

                        }
                        $model = new PlatformType();
                        $data = $model->getAll();
                        $data[0]['admin_name'] = $res['name'];
                        returnJson(200,'操作成功', $this->token_check->createToken($res['admin_id']), $data_per,[],[],$data)->send();die;
                    } else {
                        returnJson(-2001,"服务器错误")->send();die;
                    }
                } else {
                    returnJson(-2001,"服务器错误")->send();die;
                }
            } else {
                returnJson(-2001,"服务器错误")->send();die;
            }
        } else {
            returnJson(-1008,"账号或者密码错误")->send();die;
        }
    }

    /**
     * @param admin_tel         账户
     * @param admin_pwd         新密码
     * @param admin_repwd       确认密码
     * @param code              验证码
     * 非首次登陆修改密码
     */
    public function setPassword() {
        // 使用普遍的修改密码规则进行判定
        $input = input();
        $admin_pwd = isset($input['admin_pwd']) ? trim($input['admin_pwd']) : "";
        $admin_tel = isset($input['admin_tel']) ? trim($input['admin_tel']) : "";
        $code = isset($input['code']) ? trim($input['code']) : "";

        // 判定验证码是否正确或超时
        $model = new Code();
        $detail = $model->detailtel($admin_tel);
        if (empty($detail)) {
            returnJson(-2010,"请先发送验证码")->send();die;
        }
        if ((time() - $detail['create_time']) > (30 * 60)) {
            returnJson(-2010,"验证码过期")->send();die;
        }
        if ($detail['is_use'] == 1) {
            returnJson(-2010,"验证码已被使用")->send();die;
        }
        if ($detail['code'] !== $code) {
            returnJson(-2011,"验证码错误")->send();die;
        }
        $data['is_use'] = 1;
        $model->m_update($detail['code_id'], $data);

        $where['admin_tel'] = $admin_tel;
        $where['admin_status'] = 1; //是否启用
        $res = Db::name( 'admin_user' )
            ->where( $where )
            ->find();
        if ($res) {
            $updateData['admin_pwd'] = md5($admin_pwd . $res['key']);
            $updateData['start_login_time'] = time();
            $resUpdate=Db::name('admin_user')->where(['admin_id'=>$res['admin_id']])->update($updateData);
            if ($resUpdate) {
                returnJson(200,"成功")->send();die;
            } else {
                returnJson(-2001,"服务器错误")->send();die;
            }
        } else {
            returnJson(-1008,"账号或者密码错误")->send();die;
        }
    }

    /**
     * 发送验证码
     */
    public function getCode() {
        $input = input();
        $admin_tel = $input['admin_tel'];
        $code = rand(1000, 9999);
        $model = new SendSms();
        $model->sendSms($admin_tel, $code);

        $model = new Code();
        $data['admin_tel'] = $admin_tel;
        $data['code'] = $code;
        $data['is_use'] = 2;
        $data['create_time'] = time();
        $data = $model->m_insert($data);
        if ($data) {
            returnJson(200,"成功")->send();die;
        } else {
            returnJson(-2001,"服务器出错")->send();die;
        }
    }

}